// invoice.js
var iFDU = require('../../utils/iFDU.js');
var app = getApp();
Page({
  data: {
    config: app.config,
    globalData: app.globalData,

    // 是否开具发票
    invoiceType: 1,
    // 发票类型
    invoice: 0,
    invoiceCode: '',

    invoiceCheckItems: [
      { name: '单位', value: '1' },
      { name: '个人', value: '0', checked: true }
    ],

    invoiceTitle: '',
    companyList: [],
    showSearch: false,
    searchResults: []
  },

  /**
   * 选择发票类型
   */
  switchInvoiceType: function (e) {
    var invoiceType = parseInt(e.currentTarget.dataset.type);
    this.setData({
      invoiceType: invoiceType,
      invoice: 0,
    });
  },

  checkboxChange: function (e) {
    var that = this;
    var invoice = 0;
    var invoiceCheckItems = this.data.invoiceCheckItems, values = e.detail.value;
    for (var i = 0, lenI = invoiceCheckItems.length; i < lenI; ++i) {
      invoiceCheckItems[i].checked = false;

      for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (invoiceCheckItems[i].value == values[j]) {
          invoice = parseInt(invoiceCheckItems[i].value);
          invoiceCheckItems[i].checked = true;
          break;
        }
      }
    }

    this.setData({
      invoice: invoice,
      invoiceCheckItems: invoiceCheckItems,
    });
  },

  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value);

    var invoiceCheckItems = this.data.invoiceCheckItems;
    for (var i = 0, len = invoiceCheckItems.length; i < len; ++i) {
      invoiceCheckItems[i].checked = invoiceCheckItems[i].value == e.detail.value;
    }

    this.setData({
      invoiceCheckItems: invoiceCheckItems
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var invoiceCheckItems = [
      { name: '单位', value: '1' },
      { name: '个人', value: '0' }
    ];

    if (options.invoice && options.invoice == '1') {
      for (var index in invoiceCheckItems) {
        if (invoiceCheckItems[index].value == '1') {
          invoiceCheckItems[index].checked = true;
          break;
        }
      }
    } else {
      for (var index in invoiceCheckItems) {
        if (invoiceCheckItems[index].value == '0') {
          invoiceCheckItems[index].checked = true;
          break;
        }
      }
    }

    that.setData({
      invoiceCheckItems: invoiceCheckItems,
      invoiceType: options.invoice_type,
      invoice: options.invoice,
      invoiceCode: options.invoice_code,
      invoiceTitle: options.invoice_title,
    });

    app.getUserInfo(function (globalData) {
      that.setData({
        globalData: globalData
      });

      iFDU.api.doGet(
        'invoice/getInvoiceList',
        {
          userId: globalData.userId,
          invoice: 2
        },
        function (data) {
          that.setData({
            companyList: data
          });
        }
      );
    });

    
  },

  saveInvoice: function (e) {
    var that = this;
    that.setData({
      showSearch: false,
      searchResults: []
    });
    if (that.data.invoiceType == 1) {
      if (that.data.invoice == 1) {
        if (!that.data.invoiceTitle) {
          iFDU.toast.showToast({
            title: '请填写单位名称',
            mask: false
          })
          return;
        }
        if (this.data.invoiceTitle.length > 30) {
          iFDU.toast.showToast({
            title: '单位名称最多输入30个字',
            mask: false
          });
          return;
        }
        if (!that.data.invoiceCode) {
          iFDU.toast.showToast({
            title: '应国家税务部门要求，开具发票是必须填写税号',
            mask: false
          })
          return;
        }
        if (!(/^[a-zA-Z0-9]{15}$/.test(this.data.invoiceCode) || /^[a-zA-Z0-9]{18}$/.test(this.data.invoiceCode))) {
          iFDU.toast.showToast({
            title: '税号为15位或18位数字和字母',
            mask: false
          })
          return;
        }
      } else {
        if (!that.data.invoiceTitle) {
          iFDU.toast.showToast({
            title: '请填写个人名称',
            mask: false
          })
          return;
        }
        if (this.data.invoiceTitle.length > 16) {
          iFDU.toast.showToast({
            title: '个人名称最多输入16个字',
            mask: false
          });
          return;
        }
      }
    }


    iFDU.api.doGet(
      'invoice/createInvoice',
      {
        userId: that.data.globalData.userId,
        invoice_type: that.data.invoiceType,
        invoice: that.data.invoice,
        invoice_title: that.data.invoiceTitle,
        invoice_code: that.data.invoice == 0 ? '' : that.data.invoiceCode
      },
      function (data) {
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];

        var invoice = {
          invoice_type: that.data.invoiceType,
          invoice: that.data.invoice,
          invoice_title: that.data.invoiceTitle,
          invoice_code: that.data.invoice == 0 ? '' : that.data.invoiceCode
        };

        prevPage.setData({
          invoice: invoice
        })
        wx.navigateBack({

        })
      }
    );
  },

  searchCompany: function (e) {
    var val = e.detail.value;
    console.log('val', val)
    this.doSearch(val);
  },

  doSearch: function (val) {
    if (val && this.data.companyList && this.data.companyList.length > 0) {
      var searchRes = [];
      var len = this.data.companyList.length;
      for (var i = 0; i < len; i++) {
        var item = this.data.companyList[i];
        if (item['invoice_title'].indexOf(val) > -1) {
          searchRes.push(item);
        }
      }

      console.log('searchRes', searchRes)
      if (searchRes.length > 0) {
        this.setData({
          invoiceTitle: val,
          showSearch: true,
          searchResults: searchRes
        })
      } else {
        this.setData({
          showSearch: true,
          searchResults: searchRes,
          invoiceTitle: val ? val : '',
        })
      }
    } else {
      this.setData({
        searchResults: this.data.companyList,
        invoiceTitle: val ? val : '',
      })
    }
  },

  showHistoryList: function (e) {
    var val = e.detail.value;
    if (val) {
      this.doSearch(val);
      return;
    }
    this.setData({
      searchResults: this.data.companyList,
      showSearch: true
    })  
  },

  inputInvoiceCode: function (e) {
    this.setData({
      invoiceCode: e.detail.value
    })
  },

  selectCompany: function (e) {
    this.setData({
      showSearch: false,
      invoiceTitle: e.currentTarget.dataset.title,
      invoiceCode: e.currentTarget.dataset.code,
      searchResults: []
    });
  },

  closeCompanyAutoComplete: function (e) {
    this.setData({
      showSearch: false,
      searchResults: []
    });
  },

  onShareAppMessage: function (res) {
    var that = this;
    return {
      title: '爱上衬衫，从「逸见」开始…',
      imageUrl: 'http://s.i-fdu.com/runto/wxa/s/yjshare.jpeg',
      path: 'pages/home/home',
      success: function (res) {
      },
      fail: function (res) {
      }
    }
  }
})